/**
 * This class demonstrates spliting a PDF file using iText.
 * @author Frank Ji
 */
package us.gaaoc.framework.util.pdf;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import us.gaaoc.framework.model.DocPageRange;

import com.lowagie.text.Document;
import com.lowagie.text.pdf.PRAcroForm;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.SimpleBookmark;

/**
 * @author Frank Ji April 17, 2007
 * 
 * Tool that can be used to split existing PDF files.
 */
public class SplitPDF {

	/**
	 * This class can be used to split existing PDF files.
	 * 
	 * @param args
	 *            the command line arguments
	 */
	public SplitPDF() {
	};

	private String[] fileName;

	public String[] getFileName() {
		return fileName;
	}

	public void setFileName(String[] fileName) {
		this.fileName = fileName;
	}

	
	@SuppressWarnings("unchecked")
	public ByteArrayOutputStream Splitting(String[] fileName, int beginPage, int endPage) {
		ByteArrayOutputStream baos = null;
		try {
			int pageOffset = 0;
			ArrayList master = new ArrayList();
			int f = 0;			
			Document document = null;
			PdfCopy writer = null;
			
			baos = new ByteArrayOutputStream();
			while (f < fileName.length - 1) {
				// we create a reader for a certain document
				PdfReader reader = new PdfReader(fileName[f]);
				reader.consolidateNamedDestinations();
				// we retrieve the total number of pages
				int n = reader.getNumberOfPages();
				List bookmarks = SimpleBookmark.getBookmark(reader);
				if (bookmarks != null) {
					if (pageOffset != 0)
						SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset,
								null);
					master.addAll(bookmarks);
				}
				pageOffset += n;
				
				if (f == 0) {
					// step 1: creation of a document-object
					document = new Document(reader.getPageSizeWithRotation(1));
					// step 2: we create a writer that listens to the document
					writer = new PdfCopy(document,baos);
					// step 3: we open the document
					document.open();
				}
				// step 4: we add content
				PdfImportedPage page;
				for (int i = beginPage; i <= endPage; i++) {
					page = writer.getImportedPage(reader, i);
					writer.addPage(page);
				}

				PRAcroForm form = reader.getAcroForm();
				if (form != null)
					writer.copyAcroForm(reader);
				f++;
			}
			
			if (!master.isEmpty())
				writer.setOutlines(master);
			// step 5: we close the document
			document.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return baos;
	}
	
	public ByteArrayOutputStream[]  SplitFile(String file, List<DocPageRange> dprList) {
		String OriginalFile = file;
		ByteArrayOutputStream baos = null;
		ByteArrayOutputStream [] baosArray = new ByteArrayOutputStream[dprList.size()];
		int i=0;
		for (DocPageRange dpRange : dprList) {			
			String fileTitle = dpRange.getDocumentInstance().getDescription().toString().replace(' ', '_').replace("-", "_").replace(",_", "_").replace(':', '_').replace('\'', '_') + ".pdf";
			SplitPDF sp = new SplitPDF();
			String[] fileToSplit = {OriginalFile, fileTitle};
			baos = sp.Splitting(fileToSplit, dpRange.getPageRangeStart(), dpRange.getPageRangeEnd());
			baosArray[i] = baos;
			i++;
		}
		return baosArray;
	}
}
